const roleService = require('../service/SysRoleService')
const ResultUtil = require('../utils/ResultUtil')

/**
 * 业务控制层： 查询角色列表
 * @param {*} req 
 * @param {*} res 
 */
const roleList = async (req, res) => {
  const param = req.query
  let result = null
  try {
    result = await roleService.selectRoleList(param)
    res.send(ResultUtil.success(200).add(result))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 根据角色id查询角色信息
 * @param {*} req 
 * @param {*} res 
 */
const selectRoleById = async (req, res) => {
  const { id } = req.params
  try {
    const role = await roleService.selectRoleById(id)
    res.send(ResultUtil.success(200, role))
  } catch (error) {
    res.send(ResultUtil.error(500, error.message))
  }
}

/**
 * 业务控制层：添加角色信息
 * @param {*} req 
 * @param {*} res 
 */
const addRole = async (req, res) => {
  const role = req.body
  role.createdAt = new Date()
  console.log(role)
  try {
    let roleResult = await roleService.addRole(role)
    if (role.menuIds) {
      const roleIdAndMenuIds = role.menuIds.map((menuId) => {
        return { menuId, roleId: roleResult.roleId }
      })
      await roleService.bulkAddMenuIdAndRoleId(roleIdAndMenuIds)
    }
    res.send(ResultUtil.success(200, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }

}

/**
 * 业务控制层：更新角色信息
 * @param {*} req 
 * @param {*} res 
 */
const updateRole = async (req, res) => {
  const role = req.body
  role.updatedAt = new Date()
  try {
    await roleService.updateRole(role)
    if (role.menuIds) {
      await roleService.delRoleIdAndMenuIdByRoleId(role.roleId)
      const roleIdAndMenuIds = role.menuIds.map((menuId) => {
        return { menuId, roleId: role.roleId }
      })
      await roleService.bulkAddMenuIdAndRoleId(roleIdAndMenuIds)
    }
    res.send(ResultUtil.success(200, true))
  } catch (error) {
    res.send(ResultUtil.error(500, error.message))
  }
}

/**
 * 业务控制层：删除角色信息
 * @param {*} req 
 * @param {*} res 
 */
const deleteRole = async (req, res) => {
  const { id } = req.body
  try {
    await roleService.deleteRole(id)
    await roleService.delRoleIdAndMenuIdByRoleId(id)
    res.send(ResultUtil.success(204, true))
  } catch (error) {
    res.send(ResultUtil.error(500, error.message))
  }
}

/**
 * 业务控制层：根据角色id查询角色与菜单关系信息
 * @param {*} req 
 * @param {*} res 
 */
const selectRoleIdAndMenuIds = async (req, res) => {
  const { roleId } = req.query
  let result = null
  try {
    result = await roleService.selectRoleIdAndMenuIdsByRoleId(roleId)
    res.send(ResultUtil.success(200).add(result))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

module.exports = {
  roleList,
  selectRoleById,
  addRole,
  updateRole,
  deleteRole,
  selectRoleIdAndMenuIds
}